﻿using System;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SSN.Utilities.Database
{
    /// <summary>
    /// This attribue safely prevents strings from being stored in a field with a limit in a database.
    /// </summary>
    [System.AttributeUsage( System.AttributeTargets.Property )]
    public class FieldLimit : System.Attribute
    {
        private int _maxLength;

        /// <summary>
        /// Gets or sets the information about the property the attribute is applied to.
        /// </summary>
        internal PropertyInfo PropertyInfo { get; set; }
        internal object Object { get; set; }

        /// <summary>
        /// This attribue safely prevents strings from being stored in a field with a limit in a database.
        /// </summary>
        /// <param name="length">Maximum length the field can allow for the string.</param>
        public FieldLimit( int length )
        {
            _maxLength = length;
        }

        /// <summary>
        /// Tests to see if the string is within the limit.
        /// </summary>
        /// <returns>True if the string is in the limit, otherwise false.</returns>
        internal ValidationResult IsValid( )
        {
            object o = PropertyInfo.GetValue( Object, null );
            if ( !( o is string ) )
            {
                throw new Exception( "FieldLimit attribute must be applied to string." );
            }

            return new ValidationResult( )
            {
                Property = PropertyInfo.Name,
                Value = ( string ) o,
                Valid = ( ( string ) o ).Length <= _maxLength,
                Length = _maxLength
            };
        }
    }

    internal struct ValidationResult
    {
        public bool Valid;
        public string Value;
        public string Property;
        public int Length;

    }
}
